<template>
    <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <h2 class="text-center  margin-bottom">{{title}}</h2>
            <a-form layout="inline" @keyup.enter.native="searchQuery">
                <a-row :gutter="24">
                    <a-col :md="8" :sm="24">
                        <a-form-item label="收运时间">
                            <a-range-picker
                                :placeholder="['开始时间', '结束时间']"
                                v-model="rangeTime"
                                format="YYYY-MM-DD"
                                @change="handleDateChange"
                            />
                        </a-form-item>
                    </a-col>

                    <a-col :md="8" :sm="24">
                        <a-form-item label="产生单位">
                            <select-customer-list ref="selectCustomerRef" @change="changeCustomer"></select-customer-list>
                        </a-form-item>
                    </a-col>

                    <a-col :md="8" :sm="24" v-has="'query:company:select:auth'">
                        <a-form-item label="处置单位">
                            <select-company-list :companysId="queryParam.companysId" @change="changeCompany"></select-company-list>
                        </a-form-item>
                    </a-col>

                    <a-col :md="12" :sm="24">
                        <a-form-item label="区域查询">
                            <select-area ref="selectAreaRef" @change="changeArea"></select-area>
                        </a-form-item>
                    </a-col>

                </a-row>
            </a-form>
        </div>
        <!-- 查询区域-END -->

        <!-- 操作按钮区域 -->
        <div class="table-operator" style="display: flex;justify-content: space-between;align-items: center;">
            <div>
                <a-button type="primary" @click="searchQuery" icon="search">查询数据列表</a-button>
                <a-button type="primary" @click="resetForm">重置查询</a-button>
            </div>
            <div>
                <a-button type="primary" icon="printer" v-print="'#printTableList'">打印</a-button>
                <a-button type="primary" icon="download" @click="handleMwExportXlsForImages">
                    导出Excel
                </a-button>
            </div>
        </div>

        <!-- table区域-begin -->
        <div>
            <CheckboxWasteType :companysId="queryParam.companysId" @change="changeWasteType"></CheckboxWasteType>
        </div>

        <div>
            <a-table
                ref="table"
                size="middle"
                bordered
                rowKey="id"
                :columns="columns"
                :dataSource="dataSource"
                :pagination="ipagination"
                :loading="loading"
                class="j-table-force-nowrap"
                @change="handleTableChange"
            >
                <template slot="htmlSlot" slot-scope="text">
                    <div v-html="text"></div>
                </template>
                <template slot="imgSlot" slot-scope="text">
                    <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                    <img v-else :src="text" height="25px" alt style="width: auto;height: 50px;"/>
                </template>
            </a-table>
        </div>

        <div v-show="false">
            <div id="printTableList">
                <h2 style="text-align: center;font-weight: bold;">各个机构废物数据台账</h2>
                <h3 v-if="rangeTime.length">时间 ： {{rangeTime[0]}} 至 {{rangeTime[1]}}</h3>
                <a-table
                    size="small"
                    bordered
                    rowKey="id"
                    :columns="columns"
                    :dataSource="dataSource"
                    :pagination="false"
                >
                    <template slot="htmlSlot" slot-scope="text">
                        <div style="color: black !important;" v-html="text"></div>
                    </template>
                </a-table>
            </div>
        </div>

    </a-card>
</template>

<script>
/**
 * create by Jane
 * 机构台账信息
 */
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import SelectArea from '@/components/Jane/SelectArea'
import SelectCompanyList from '@/components/Jane/SelectCompanyList'
import SelectCustomerList from '@/components/Jane/SelectCustomerList'
import CheckboxWasteType from '@/components/Jane/CheckboxWasteType'
import waste from '@api/waste'

export default {
    name: 'CustomerBookManager',
    mixins: [JeecgListMixin, mixinDevice],
    components: {
        SelectArea,
        SelectCompanyList,
        SelectCustomerList,
        CheckboxWasteType,
    },
    data() {
        return {
            title: '各个机构废物数据台账',
            rangeTime: [],
            queryParam: {
                creatTimeBegin: null,
                creatTimeEnd: null
            },
            // 表头
            columns: [],
            url: {
                list: '/hc/hcRecycleRecord/getCustomerStandingBook',   // 小彭接口 3.0
                exportXlsUrlOkForImages: '/hc/hcRecycleRecord/exportCustomerStandingBook'  // 小彭接口 3.0
            },
            wasteTypeStatistic: [], // 废物分类数据统计
            wasteTypeList: [], // 废物类型列表 (原始数据)
            wasteId: []  // 选择的废物
        }
    },
    mounted() {

    },
    methods: {
        // 初始化数据
        initData: function() {
            for (let i in this.queryParam) {
                this.queryParam[i] = ''
            }
            // 获取到用户登陆的信息
            let userInfo = this.$store.getters.userInfo
            if (userInfo.companysId) {
                this.queryParam.companysId = userInfo.companysId
            }
            // 如果用户存在区县编码、处置单位Id编号，则赋值
            if (userInfo.cityCode) {
                this.queryParam.cityCode = userInfo.cityCode
            }
            if (userInfo.areaCode) {
                this.queryParam.areaCode = userInfo.areaCode
            }
            let ref = this.$refs.selectAreaRef
            if (ref && ref.clearSelectArea != undefined) {
                ref.clearSelectArea()
            }
            let refCus = this.$refs.selectCustomerRef;
            if(refCus && refCus.clearSelectCustomer != undefined){
                refCus.clearSelectCustomer();
            }
            this.queryParam.creatTimeBegin = new Date().MonthFirstDay()
            this.queryParam.creatTimeEnd = new Date().MonthLastDay()
            this.rangeTime = [this.queryParam.creatTimeBegin, this.queryParam.creatTimeEnd]

        },

        async initDictConfig() {
            this.initData()
            this.setColumns()
        },
        handleDateChange(value, dateString) {
            this.rangeTime = dateString
            if (dateString[0]) {
                this.queryParam.creatTimeBegin = dateString[0]
            }
            if (dateString[1]) {
                this.queryParam.creatTimeEnd = dateString[1]
            }
        },
        async changeCustomer(value, option) {
            this.queryParam.customerNumber = value

        },

        async changeCompany(value,option) {
            this.queryParam.companysId = value;
            // 以下代码是解决在wasteId还没赋值前会在JeecgListMixin提前发送一次请求的bug
            let params = {}
            if(this.queryParam.companysId){
                params['companysId'] = this.queryParam.companysId;
            }
            let data = await waste.getWasteTypeListByCompanyId(params);
            let list = []
            data[0].children.forEach((val,key)=>{
                list.push(val.id)
            })
            this.wasteId = list
            this.searchQuery()
        },
        // 废物类型选择改变
        async changeWasteType(info,wasteList) {
            this.wasteId = info.ids;
            this.queryParam.wasteId = info.ids.join(',');
            this.wasteTypeList = wasteList;
            this.setColumns()
            // this.loadData()
            this.searchQuery()
        },
        searchQuery: function() {
            this.queryParam.wasteId = this.wasteId.join(',')
            this.loadData(1)
        },
        async changeArea({ area, city }) {
            if (city) {
                this.queryParam.cityCode = city
            }
            if (area) {
                this.queryParam.areaCode = area
            }
        },
        // 重置筛选表单
        resetForm: function() {
            this.initData();
            this.searchQuery();
        },

        // 设置表格头部信息
        setColumns() {
            let data = this.wasteTypeList
            let cols = []
            data.forEach((item, index) => {
                if (item.wasteTypeName) {
                    let child = [];
                    (item['children'] || []).forEach((val, i) => {
                        let info = this.wasteId.find(v => v === val.id)
                        if (info) {
                            // 塑料输液瓶（袋）、玻璃输液瓶（袋）单位换成kg
                            if(val.id == "1366228898901467138" || val.id == "1366274806234079234"){
                                val.priceUnit = "kg"
                            }
                            child.push({
                                title: val.wasteTypeName,
                                dataIndex: 'id',
                                key: `${index}-${i}`,
                                children: [
                                    {
                                        title: '产生量',
                                        dataIndex: 'id',
                                        key: `${index}-${i}-0`,
                                        children: [
                                            {
                                                title: '袋/箱数',
                                                align: 'center',
                                                dataIndex: 'id',
                                                key: `${index}-${i}-0-1`,
                                                customRender: function(vv, waste, index) {
                                                    let info = (waste['maps']).find((v) => v.wasteId === val.id)
                                                    if (info) {
                                                        const obj = {
                                                            children: `${info.totalWasteOriginalNumber || ''}`,
                                                            attrs: {}
                                                        }
                                                        if (waste.colSpan) {
                                                            obj.children =
                                                                <
                                                                    div
                                                                    style = 'color:red;font-weight:600;' > {
                                                                    info
                                                                        .totalWasteOriginalNumber || ''
                                                                } < /div>;
                                                                    }
                                                                    return obj
                                                                    }
                                                                    return ' '
                                                                    }
                                                                    },
                                                                    {
                                                                        title: `废物量${val.priceUnit ? `(${val.priceUnit})` : ''}`,
                                                                        align: 'center',
                                                                        dataIndex: 'id',
                                                                        key: `${index}-${i}-0-2`,
                                                                        customRender: function(vv, waste, index) {
                                                                        let info = (waste['maps']).find((v) => v.wasteId === val.id)
                                                                        if (info) {
                                                                        const obj = {
                                                                        children: `${info.totalWasteOriginalValue || ''}`,
                                                                        attrs: {}
                                                                    }
                                                                        if (waste.colSpan) {
                                                                        obj.children =
                                                                        <
                                                                        div
                                                                        style = 'color:red;font-weight:600;' > {
                                                                        info
                                                                            .totalWasteOriginalValue || ''
                                                                    }
                                                                        {
                                                                            val.priceUnit ? `(${val.priceUnit})` : ''
                                                                        }
                                                                        <
                                                                        /div>;
                                                                        }
                                                                        return obj
                                                                        }
                                                                        return ''
                                                                        }
                                                                        }
                                                                        ]
                                                                        },
                                                                        {
                                                                            title: '处置量',
                                                                            dataIndex: 'id',
                                                                            key: `${index}-${i}-1`,
                                                                            children: [
                                                                        {
                                                                            title: '袋/箱数',
                                                                            align: 'center',
                                                                            dataIndex: 'id',
                                                                            key: `${index}-${i}-1-1`,
                                                                            customRender: function(vv, waste, index) {
                                                                            let info = (waste['maps']).find((v) => v.wasteId === val.id)
                                                                            if (info) {
                                                                            const obj = {
                                                                            children: `${info.totalWastePresentNumber || ''}`,
                                                                            attrs: {}
                                                                        }
                                                                            if (waste.colSpan) {
                                                                            obj.children =
                                                                            <
                                                                            div
                                                                            style = 'color:red;font-weight:600;' > {
                                                                            info
                                                                                .totalWastePresentNumber || ''
                                                                        } < /div>;
                                                                            }
                                                                            return obj
                                                                            }
                                                                            return ' '
                                                                            }
                                                                            },
                                                                            {
                                                                                title: `废物量${val.priceUnit ? `(${val.priceUnit})` : ''}`,
                                                                                align: 'center',
                                                                                dataIndex: 'id',
                                                                                key: `${index}-${i}-1-2`,
                                                                                customRender: function(vv, waste, index) {
                                                                                let info = (waste['maps']).find((v) => v.wasteId === val.id)
                                                                                if (info) {
                                                                                const obj = {
                                                                                children: `${info.totalWastePresentValue || ''}`,
                                                                                attrs: {}
                                                                            }
                                                                                if (waste.colSpan) {
                                                                                obj.children =
                                                                                <
                                                                                div
                                                                                style = 'color:red;font-weight:600;' > {
                                                                                info
                                                                                    .totalWastePresentValue || ''
                                                                            }
                                                                                {
                                                                                    val.priceUnit ? `(${val.priceUnit})` : ''
                                                                                }
                                                                                <
                                                                                /div>;
                                                                                }
                                                                                return obj
                                                                                }
                                                                                return ''
                                                                                }
                                                                                }
                                                                                ]
                                                                                }
                                                                                ]
                                                                                })
                                                                                }
                                                                                })
                                                                                if (child.length) {
                                                                                let obj = {
                                                                                title: item.wasteTypeName,
                                                                                dataIndex: 'id',
                                                                                key: `${index}`,
                                                                                children: child
                                                                            }
                                                                                cols.push(obj)
                                                                            }
                                                                                }
                                                                                })
                                                                                this.columns = [
                                                                                {
                                                                                    title: '序号',
                                                                                    dataIndex: 'id',
                                                                                    key: 'rowIndex',
                                                                                    width: 60,
                                                                                    align: 'center',
                                                                                    scopedSlots: { customRender: 'htmlSlot' },
                                                                                    customRender: (text, row, index) => {
                                                                                    const obj = {
                                                                                    children: parseInt(index) + 1,
                                                                                    attrs: {}
                                                                                }
                                                                                    if (row.colSpan) {
                                                                                    obj.children =
                                                                                    <
                                                                                    div
                                                                                    style = 'color:red;font-weight:600;' > 合计 < /div>;
                                                                                    obj.attrs.colSpan = 3
                                                                                    }
                                                                                    return obj
                                                                                    }
                                                                                    },
                                                                                    // {
                                                                                    //     title: '日期',
                                                                                    //     align: 'center',
                                                                                    //     dataIndex: 'createTime',
                                                                                    //     key: 'createTime',
                                                                                    //     customRender: (value, row, index) => {
                                                                                    //         const obj = {
                                                                                    //             children: !value ? '' : value.length > 10 ? value.substr(0, 10) : value,
                                                                                    //             attrs: {}
                                                                                    //         }
                                                                                    //         if (row.colSpan) {
                                                                                    //             obj.attrs.colSpan = 0
                                                                                    //         }
                                                                                    //         return obj
                                                                                    //     }
                                                                                    // },
                                                                                    {
                                                                                        title: '机构名称',
                                                                                        align: 'center',
                                                                                        dataIndex: 'customerName',
                                                                                        key: 'customerName',
                                                                                        customRender: (value, row, index) => {
                                                                                            const obj = {
                                                                                                children: value,
                                                                                                attrs: {}
                                                                                            }
                                                                                            if (row.colSpan) {
                                                                                                obj.attrs.colSpan = 0
                                                                                            }
                                                                                            return obj
                                                                                        }
                                                                                    },
                                                                                    ...cols
                                                                                    ]
                                                                                },


                                                                                    handleMwExportXlsForImages() {
                                                                                    if (this.wasteId.length) {
                                                                                    this.queryParam.wasteId = this.wasteId.join(',')
                                                                                    let nameList = []
                                                                                    this.wasteTypeList.forEach((item) => {
                                                                                    let child = item['children'] || [];
                                                                                    child.forEach((val) => {
                                                                                    // 如果是选中的状态，则追加在wasteList中
                                                                                    if(val.checked){
                                                                                    nameList.push({...val});
                                                                                }
                                                                                })
                                                                                })
                                                                                    let wasteName = []
                                                                                    this.wasteId.forEach((val) => {
                                                                                    let info = nameList.find(item => val === item.id)
                                                                                    if (info) {
                                                                                    wasteName.push(info['wasteTypeName'])
                                                                                }
                                                                                })
                                                                                    this.queryParam.wasteName = wasteName.join(',')
                                                                                } else {
                                                                                    this.$message.warning('选择至少一个废物类型导出！')
                                                                                    return
                                                                                }
                                                                                    let param = { ...this.queryParam }

                                                                                    let name = `机构台账-${new Date().FormatDate()}.xls`
                                                                                    downloadFile(this.url.exportXlsUrlOkForImages, name, param)
                                                                                }

                                                                                    }
                                                                                    }
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>